package com.ftrend.printdemo.mhttemplate;

import android.graphics.Bitmap;
import android.graphics.Color;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.HashMap;
import java.util.Map;

/**
 * 条码
 *
 * @author mapleaf
 * @date 2022/09/07
 */
public class BarCodeElement {
    private final String text;
    private final BarcodeFormat format;
    private int width = 84;
    private int height = 84;

    /**
     * 创建条码
     *
     * @param text   文本
     * @param format 条码格式
     */
    public BarCodeElement(String text, BarcodeFormat format) {
        this.text = text;
        this.format = format;
    }

    public BarcodeFormat getFormat() {
        return format;
    }

    public String getText() {
        return text;
    }

    /**
     * 设置首选宽高，不代表最终尺寸
     *
     * @param w 首选图片宽度
     * @param h 都选图片高度
     */
    public void setSize(int w, int h) {
        this.width = w;
        this.height = h;
    }

    public Bitmap toBitmap() throws WriterException {
        MultiFormatWriter writer = new MultiFormatWriter();
        Map<EncodeHintType, Integer> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix matrix = writer.encode(text, format, width, height, hints);
        Bitmap bitmap = Bitmap.createBitmap(matrix.getWidth(), matrix.getHeight(), Bitmap.Config.RGB_565);
        for (int i = 0; i < matrix.getWidth(); i++) {
            for (int j = 0; j < matrix.getHeight(); j++) {
                if (matrix.get(i, j)) {
                    bitmap.setPixel(i, j, Color.BLACK);
                } else {
                    bitmap.setPixel(i, j, Color.WHITE);
                }
            }
        }
        return bitmap;
    }
}
